package com.easy.util;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;
import java.util.UUID;

public class EmailUtil {
    private static final String FROM="2386857574@qq.com";
    private static final String AUTH_CODE="ujzjurbldfxbdjci";
    private static final String HOST="smtp.qq.com";
    private static final String PORT="465";
    private static final Session session;

    static{
        Properties props=new Properties();
        props.put("mail.smtp.host",HOST);
        props.put("mail.smtp.port",PORT);
        props.put("mail.smtp.auth","true");
        props.put("mail.smtp.ssl.enable","true");
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM,AUTH_CODE);
            }
        });
    }

    // 发送验证码邮件
    public static String sendVerificationCode(String to, String code){
        Message message = new MimeMessage(session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
            message.setSubject("佰家珍铭系统验证码");
            message.setContent("<h1 style='color:red'>验证码："+code+"</h1><p>验证码5分钟内有效</p>","text/html;charset=utf-8");
            Transport.send(message);
            return "发送成功";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "发送失败: " + e.getMessage();
        }
    }

    public static void sendEmail(String to){
        String code = UUID.randomUUID().toString().substring(0, 6);
        sendVerificationCode(to, code);
    }

    public static boolean checkEmail(String textA,String textB){
        return textA.equals(textB);
    }

    public static void main(String[] args) {
        sendEmail("2386857574@qq.com");
    }
}